<template>
  <div class="order-statistics-container">
    <h2>订单统计</h2>
    <div ref="chartContainer" class="chart-container"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 图表容器引用
const chartContainer = ref(null)
let chart = null

// 获取订单统计数据
const fetchOrderStatistics = async () => {
  try {
    const response = await axios({
      url: '/api/orders/statistics/recent',
      method: 'get',
      headers: {
        Authorization: localStorage.getItem('token')
      }
    })

    // 检查响应数据
    if (response && response.data) {
      const res = response.data
      if (res.code === 200 && res.data) {
        const data = res.data
        // 确保 dates 和 counts 存在
        if (data.dates && data.counts) {
          renderChart(data.dates, data.counts)
        } else {
          console.error('返回的数据格式不正确:', data)
        }
      } else {
        console.error('请求失败或返回数据格式不正确:', res)
      }
    } else {
      console.error('响应数据为空:', response)
    }
  } catch (error) {
    console.error('获取订单统计数据失败:', error)
  }
}

// 渲染图表
const renderChart = (dates, counts) => {
  if (!chartContainer.value) return

  // 初始化图表
  chart = echarts.init(chartContainer.value)

  // 图表配置
  const option = {
    title: {
      text: '最近7天订单统计'
    },
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: dates
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: counts,
        type: 'line',
        smooth: true,
        areaStyle: {}
      }
    ]
  }

  // 设置图表配置
  chart.setOption(option)

  // 监听窗口大小变化，自适应图表
  const handleResize = () => {
    if (chart) {
      chart.resize()
    }
  }

  window.addEventListener('resize', handleResize)
}

// 组件挂载后获取数据并渲染图表
onMounted(() => {
  fetchOrderStatistics()
})
</script>

<style scoped>
.order-statistics-container {
  padding: 20px;
}

.chart-container {
  width: 100%;
  height: 500px;
  margin-top: 20px;
}

h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>
